package com.powergisol.gis.service.impl;
import	java.io.File;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.fasterxml.jackson.core.type.TypeReference;
import com.powergisol.gis.Enum.ServiceTypeEnum;
import com.powergisol.gis.dao.TabDataSettingMapper;
import com.powergisol.gis.dao.TabMouldMapper;
import com.powergisol.gis.dao.TabProjectMapper;
import com.powergisol.gis.entity.*;
import com.powergisol.gis.listener.*;
import com.powergisol.gis.service.ExcelInService;
import com.powergisol.gis.service.SaveDataService;
import com.powergisol.gis.util.*;
import com.powergisol.gis.vo.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ExcelInServiceImpl implements ExcelInService {

    //单次入库数据最大条数
    private final static int MAX_NUM = 2000;

    @Value("${earth-url}")
    private String earthUrl;

    static double M_PI = Math.PI;

    @Autowired
    private TabDataSettingMapper tabDataSettingMapper;

    @Autowired
    private SaveDataService saveDataService;

    @Autowired
    private TabMouldMapper tabMouldMapper;

    @Resource
    private CacheManager cacheManager;

    @Autowired
    private TabProjectMapper tabProjectMapper;


    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Result easyexcelImport(MultipartFile excelFile, SzZkCmdStandardVo vo, TabUserVo tabUserVo) {
        Result result = new Result();
        Map<String,Object> map = new HashMap<>();
        Integer settingId = null;
        Integer serviceId = null;
        try {
            //导入参数设置
            if(null == vo.getTitleRows()){
                return result.failure(-1,"标题所在行需指定");
            }
            String uuid = vo.getUuid();
            String userDir = System.getProperty("user.dir");
            String fileName1 = excelFile.getName();
            vo.setFileName(fileName1);
            if(null == vo.getStartRows()){
                vo.setStartRows(vo.getTitleRows()+1);
            }
            // 获取文件名
            String fileName = excelFile.getOriginalFilename();
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            vo.setFileName(fileName.substring(0,fileName.lastIndexOf(".")));
            userDir = userDir.substring(0,userDir.lastIndexOf(File.separator))+File.separator+"Upload"+File.separator+"excel"+File.separator+uuid+suffixName;

            //发布服务
            SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMddHHmmss");
            String serviceName = vo.getFileName()+sdf1.format(new Date());
            TabServiceVo tabServiceVo = new TabServiceVo();
            tabServiceVo.setServiceUrl(earthUrl+serviceName);
            //根据用户查询用户
            tabServiceVo.setUserId(tabUserVo.getId());

            tabServiceVo.setName(serviceName);
            tabServiceVo.setReleaseTime(new Date());
            tabServiceVo.setServiceType(ServiceTypeEnum.ZKEXCEL.getValue());
            tabServiceVo.setUuid(vo.getUuid());

            tabDataSettingMapper.saveService(tabServiceVo);
            tabDataSettingMapper.saveUserService(tabServiceVo.getUserId(),tabServiceVo.getId());
            serviceId = tabServiceVo.getId();
            TabDataSetting dataSetting = new TabDataSetting();
            dataSetting.setUuid(vo.getUuid());
            dataSetting.setCreateUser(tabUserVo.getName());

            dataSetting.setTitleRow(vo.getTitleRows());
            dataSetting.setDataStartRow(null == vo.getStartRows()?vo.getTitleRows()+1:vo.getStartRows());
            if(null != vo.getReadRows()){
                dataSetting.setDataEndRow(vo.getReadRows());
            }
            //总条数
            Integer totalNum = dataSetting.getDataEndRow()-dataSetting.getDataStartRow()+1;
            dataSetting.setDataType(1);
            dataSetting.setDataUrl(userDir);
            dataSetting.setCreateTime(new Date());
            dataSetting.setServiceId(serviceId);

            TabCoordinateSystem system = new TabCoordinateSystem();
            if(1 == vo.getIsChange()){
                system = tabMouldMapper.getCoorByName(vo.getCoorName());
                try{
                    XyChangeUtil.change(1d, 1d,system.getCoorChangeLat());
                }catch (Exception e){
                    e.printStackTrace();
                    return result.failure(-1,"请选择正确的坐标转换公式");
                }
                dataSetting.setCoorName(system.getCoorName());
            }
            //保存入库
            tabDataSettingMapper.saveDataSetting(dataSetting);
            settingId = dataSetting.getId();
            ExcelModelListener listener = new ExcelModelListener(vo,saveDataService,settingId,cacheManager,system);
            Sheet sheet = new Sheet(1, 0);
            EasyExcelFactory.readBySax(excelFile.getInputStream(), sheet,listener);
            Cache cache = cacheManager.getCache("cache-data");
            TabProject tp = cache.get(vo.getUuid()+"project",TabProject.class);
            TaskResultVo resultVo = cache.get(vo.getUuid()+"result",TaskResultVo.class);
            //去重
            List<TabZuankong> zkListNew = resultVo.getListZk().stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getTCMC_() + ";" + o.getTCCDSD_()+";"+o.getZKX()+":"+o.getZKY()))), ArrayList::new));
            //如果工程不存在则删除已有数据，导入失败
            if(null == tp || zkListNew.isEmpty() || resultVo.getListTc().isEmpty()){
                if(null != serviceId) {
                    tabDataSettingMapper.delTabDataSetting(serviceId);
                    tabDataSettingMapper.delTabService(serviceId);
                    tabDataSettingMapper.delUserService(serviceId);
                }
                return result.failure(-1, "导入数据缺少必要信息");
            }
            //保存项目
            tp.setSettingId(settingId);
            tabProjectMapper.saveProject(tp);

            //保存数据
            Integer zkNum = zkListNew.size()/MAX_NUM + (zkListNew.size()%MAX_NUM>0?1:0);
            saveBatch(zkNum,zkListNew);
            Integer tcNum = resultVo.getListTc().size()/MAX_NUM + (resultVo.getListTc().size()%MAX_NUM>0?1:0);
            saveBatch(tcNum,resultVo.getListTc());
            Integer swNum = resultVo.getListSw().size()/MAX_NUM + (resultVo.getListSw().size()%MAX_NUM>0?1:0);
            saveBatch(swNum,resultVo.getListSw());

            tabServiceVo.setState(1);
            tabServiceVo.setFileUrl(userDir);
            tabDataSettingMapper.updateService(tabServiceVo);
            File file = new File(userDir);
            // 检测是否存在目录
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            excelFile.transferTo(file);

            Integer sbNum = resultVo.getListFailed().size();
            map.put("失败数据",resultVo.getListFailed());
            map.put("成功条数",totalNum-sbNum);
            //返回信息
            map.put("tabDataSetting",dataSetting);
            map.put("tabService",tabServiceVo);
            map.put("tabProject",tp);
        }catch (Exception e){
            e.printStackTrace();
            //删除已保存的数据(tab_service\tab_user_service\tab_data_setting\tab_zuankong\tab_zk_tuceng\tab_zk_shuiwei)
            if(null != serviceId) {
                tabDataSettingMapper.delTabDataSetting(serviceId);
                tabDataSettingMapper.delTabService(serviceId);
                tabDataSettingMapper.delUserService(serviceId);
            }
            if(null != settingId){
                tabDataSettingMapper.delTabSw(settingId);
                tabDataSettingMapper.delTabTc(settingId);
                tabDataSettingMapper.delTabZk(settingId);
                tabDataSettingMapper.delTabProject(settingId);
            }
            return result.failure(-1, "系统错误");
        }
        result.success(map);
        return result;
    }

    private void saveBatch(Integer num,Object o){
        List<Object> list = (List)o;
        for (int i = 0; i < num; i++) {
            if((i+1)==num){
                saveDataService.saveBatch(list.subList(i*MAX_NUM,list.size()));
            }else{
                saveDataService.saveBatch(list.subList(i*MAX_NUM,(i+1)*MAX_NUM));
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Result cnyImport(MultipartFile excelFile, CnyZkExcelStandardVo vo, TabUserVo tabUserVo) {
        Result result = new Result();
        Map<String,Object> map = new HashMap<>();
        Integer settingId = null;
        Integer serviceId = null;
        try {
            String uuid = vo.getUuid();
            String userDir = System.getProperty("user.dir");

            //上传文件
            result = FileUpload.fileUpload(excelFile,userDir,uuid);
            userDir = (String)result.getData();


            String fileName1 = excelFile.getName();
            vo.setFileName(fileName1);
            // 获取文件名
            String fileName = excelFile.getOriginalFilename();
            // 获取文件的后缀名
            vo.setFileName(fileName.substring(0,fileName.lastIndexOf(".")));

            //发布服务
            SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMddHHmmss");
            String serviceName = vo.getFileName()+sdf1.format(new Date());
            TabServiceVo tabServiceVo = new TabServiceVo();
            tabServiceVo.setServiceUrl(earthUrl+serviceName);
            tabServiceVo.setUserId(tabUserVo.getId());

            tabServiceVo.setName(serviceName);
            tabServiceVo.setReleaseTime(new Date());
            tabServiceVo.setServiceType(ServiceTypeEnum.ZKEXCEL.getValue());
            tabServiceVo.setUuid(vo.getUuid());

            tabDataSettingMapper.saveService(tabServiceVo);
            tabDataSettingMapper.saveUserService(tabServiceVo.getUserId(),tabServiceVo.getId());
            serviceId = tabServiceVo.getId();
            TabDataSetting dataSetting = new TabDataSetting();
            dataSetting.setUuid(vo.getUuid());
            dataSetting.setCreateUser(tabUserVo.getName());
            dataSetting.setDataType(1);
            dataSetting.setDataUrl(userDir);
            dataSetting.setCreateTime(new Date());
            dataSetting.setServiceId(serviceId);
            TabCoordinateSystem system = new TabCoordinateSystem();
            if(1 == vo.getIsChange()){
                system = tabMouldMapper.getCoorByName(vo.getCoorName());
                dataSetting.setCoorName(vo.getCoorName());
            }
            //保存入库
            tabDataSettingMapper.saveDataSetting(dataSetting);
            settingId = dataSetting.getId();
            //解压文件
            String zipUrl = userDir.substring(0,userDir.lastIndexOf(File.separator))+File.separator+uuid;
            ZipUtil.unZip(userDir,zipUrl);
            List<File> listFile = FileUtil.recursionFile(zipUrl,null);
            System.out.println("解析开始");
            String projectName = null;
            Cache cache = cacheManager.getCache("cache-data");
            //失败数据
            StringBuffer sb = new StringBuffer();
             Integer cgNum = 0;
            List<ExcelInFailedDataVo> listFailed = new ArrayList<>();
             for (File file : listFile){
                 String excelName = file.getName();
                 try{
                     CnyExcelModelListener3 listener = new CnyExcelModelListener3(vo,saveDataService,settingId,cacheManager,system,projectName,excelName);
                     Sheet sheet = new Sheet(1, 0);
                     EasyExcelFactory.readBySax(new FileInputStream(file.getAbsolutePath()), sheet,listener);
                     if(null != cache.get(vo.getUuid() +"sb")){
                         TaskResultVo taskResultVo = cache.get(vo.getUuid() +"sb",TaskResultVo.class);
                         listFailed.addAll(taskResultVo.getListFailed());
                     }else{
                         cgNum = cgNum + 1;
                     }
                 }catch (Exception e){
                     System.out.println(excelName);
                     sb.append(excelName+";");
                 }

             }
            System.out.println("解析结束");
            map.put("成功条数",cgNum);
            map.put("失败数据",listFailed);
            tabServiceVo.setState(1);
            tabServiceVo.setFileUrl(userDir);
            tabDataSettingMapper.updateService(tabServiceVo);

            //保存项目
            TabProject tp = new TabProject();
            tp.setGCMC(vo.getFileName());
            if(null != cache.get(vo.getUuid()+"projectName")){
                projectName = cache.get(vo.getUuid()+"projectName",String.class);
                if(null != projectName && !("").equals(projectName)){
                    tp.setGCMC(projectName);
                    tp.setGCBH(projectName);
                }
            }
            tp.setSettingId(settingId);
            tabProjectMapper.saveProject(tp);
            //返回信息
            map.put("tabDataSetting",dataSetting);
            map.put("tabService",tabServiceVo);
            map.put("tabProject",tp);
        }catch (Exception e){
            e.printStackTrace();
            //删除已保存的数据(tab_service\tab_user_service\tab_data_setting\tab_zuankong\tab_zk_tuceng\tab_zk_shuiwei)
            if(null != serviceId) {
                tabDataSettingMapper.delTabDataSetting(serviceId);
                tabDataSettingMapper.delTabService(serviceId);
                tabDataSettingMapper.delUserService(serviceId);
            }
            if(null != settingId){
                tabDataSettingMapper.delTabSw(settingId);
                tabDataSettingMapper.delTabTc(settingId);
                tabDataSettingMapper.delTabZk(settingId);
                tabDataSettingMapper.delTabProject(settingId);
            }
            return result.failure(500, "系统错误");
        }
        result.success(map);
        return result;
    }
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Result cnyImport1(MultipartFile excelFile, CnyZkExcelStandardVo vo, TabUserVo tabUserVo) {
        Result result = new Result();
        Map<String,Object> map = new HashMap<>();
        Integer settingId = null;
        Integer serviceId = null;
        try {
            String uuid = vo.getUuid();
            String userDir = System.getProperty("user.dir");

            //上传文件
            result = FileUpload.fileUpload(excelFile,userDir,uuid);
            userDir = (String)result.getData();


            String fileName1 = excelFile.getName();
            vo.setFileName(fileName1);
            // 获取文件名
            String fileName = excelFile.getOriginalFilename();
            // 获取文件的后缀名
            vo.setFileName(fileName.substring(0,fileName.lastIndexOf(".")));

            //发布服务
            SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMddHHmmss");
            String serviceName = vo.getFileName()+sdf1.format(new Date());
            TabServiceVo tabServiceVo = new TabServiceVo();
            tabServiceVo.setServiceUrl(earthUrl+serviceName);
            //根据用户查询用户
            tabServiceVo.setUserId(tabUserVo.getId());

            tabServiceVo.setName(serviceName);
            tabServiceVo.setReleaseTime(new Date());
            tabServiceVo.setServiceType(ServiceTypeEnum.ZKEXCEL.getValue());
            tabServiceVo.setUuid(vo.getUuid());

            tabDataSettingMapper.saveService(tabServiceVo);
            tabDataSettingMapper.saveUserService(tabServiceVo.getUserId(),tabServiceVo.getId());
            serviceId = tabServiceVo.getId();
            TabDataSetting dataSetting = new TabDataSetting();
            dataSetting.setUuid(vo.getUuid());
            dataSetting.setCreateUser(tabUserVo.getName());
            dataSetting.setDataType(1);
            dataSetting.setDataUrl(userDir);
            dataSetting.setCreateTime(new Date());
            dataSetting.setServiceId(serviceId);
            TabCoordinateSystem system = new TabCoordinateSystem();
            if(1 == vo.getIsChange()){
                system = tabMouldMapper.getCoorByName(vo.getCoorName());
                dataSetting.setCoorName(vo.getCoorName());
            }
            //保存入库
            tabDataSettingMapper.saveDataSetting(dataSetting);
            settingId = dataSetting.getId();
            //解压文件
            String zipUrl = userDir.substring(0,userDir.lastIndexOf(File.separator))+File.separator+uuid;
            ZipUtil.unZip(userDir,zipUrl);
            List<File> listFile = FileUtil.recursionFile(zipUrl,null);
            System.out.println("解析开始");
            String projectName = null;
            Cache cache = cacheManager.getCache("cache-data");
            //失败数据
            StringBuffer sb = new StringBuffer();
            Integer cgNum = 0;
            List<ExcelInFailedDataVo> listFailed = new ArrayList<>();
            for (File file : listFile){
                String excelName = file.getName();
                try{
                    CnyExcelModelListener listener = new CnyExcelModelListener(vo,saveDataService,settingId,cacheManager,system,excelName);
                    Sheet sheet = new Sheet(1, 0);
                    EasyExcelFactory.readBySax(new FileInputStream(file.getAbsolutePath()), sheet,listener);
                    if(null != cache.get(vo.getUuid() +"sb")){
                        TaskResultVo taskResultVo = cache.get(vo.getUuid()  +"sb",TaskResultVo.class);
                        listFailed.addAll(taskResultVo.getListFailed());
                    }else{
                        cgNum = cgNum + 1;
                    }
                }catch (Exception e){
                    sb.append(excelName+";");
                }
            }
            if(("0").equals(cgNum.toString()) ){
                tabDataSettingMapper.delTabDataSetting(serviceId);
                tabDataSettingMapper.delTabService(serviceId);
                tabDataSettingMapper.delUserService(serviceId);
            }else{
                tabServiceVo.setState(1);
                tabServiceVo.setFileUrl(userDir);
                tabDataSettingMapper.updateService(tabServiceVo);
                //保存项目
                TabProject tp = new TabProject();
                tp.setGCMC(vo.getFileName());
                tp.setSettingId(settingId);
                tabProjectMapper.saveProject(tp);
                map.put("tabProject",tp);
            }
            System.out.println("解析结束");
            map.put("成功条数",cgNum);
            map.put("失败数据",listFailed);

            //返回信息
            map.put("tabDataSetting",dataSetting);
            map.put("tabService",tabServiceVo);
        }catch (Exception e){
            e.printStackTrace();
            //删除已保存的数据(tab_service\tab_user_service\tab_data_setting\tab_zuankong\tab_zk_tuceng\tab_zk_shuiwei)
            if(null != serviceId) {
                tabDataSettingMapper.delTabDataSetting(serviceId);
                tabDataSettingMapper.delTabService(serviceId);
                tabDataSettingMapper.delUserService(serviceId);
            }
            if(null != settingId){
                tabDataSettingMapper.delTabSw(settingId);
                tabDataSettingMapper.delTabTc(settingId);
                tabDataSettingMapper.delTabZk(settingId);
                tabDataSettingMapper.delTabProject(settingId);
            }
            return result.failure(500, "系统错误");
        }
        result.success(map);
        return result;
    }

    @Override
    public Result liangImport(MultipartFile excelFile, ExcelInportBaseVo vo, TabUserVo tabUserVo) {
        Result result = new Result();
        Map<String,Object> map = new HashMap<>();
        try {
            String uuid = vo.getUuid();
            String userDir = System.getProperty("user.dir");

            //上传文件
            result = FileUpload.fileUpload(excelFile,userDir,uuid);
            userDir = (String)result.getData();


            String fileName1 = excelFile.getName();
            vo.setFileName(fileName1);
            // 获取文件名
            String fileName = excelFile.getOriginalFilename();
            // 获取文件的后缀名
            vo.setFileName(fileName.substring(0,fileName.lastIndexOf(".")));

            //发布服务
            SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMddHHmmss");
            String serviceName = vo.getFileName()+sdf1.format(new Date());
            TabServiceVo tabServiceVo = new TabServiceVo();
            tabServiceVo.setServiceUrl(earthUrl+serviceName);
            //根据用户查询用户
            tabServiceVo.setUserId(tabUserVo.getId());

            tabServiceVo.setName(serviceName);
            tabServiceVo.setReleaseTime(new Date());
            tabServiceVo.setServiceType(ServiceTypeEnum.LIANG.getValue());
            tabServiceVo.setUuid(vo.getUuid());

            tabDataSettingMapper.saveService(tabServiceVo);
            tabDataSettingMapper.saveUserService(tabServiceVo.getUserId(),tabServiceVo.getId());
            TabCoordinateSystem system = new TabCoordinateSystem();
            if(1 == vo.getIsChange()){
                system = tabMouldMapper.getCoorByName(vo.getCoorName());
            }
            //解压文件
            String zipUrl = userDir.substring(0,userDir.lastIndexOf(File.separator))+File.separator+uuid;
            ZipUtil.unZip(userDir,zipUrl);
            List<File> listFile = FileUtil.recursionFile(zipUrl,null);
            System.out.println("解析开始");
            Cache cache = cacheManager.getCache("cache-data");
            //失败数据
            StringBuffer sb = new StringBuffer();
            Integer cgNum = 0;
            List<ExcelInFailedDataVo> listFailed = new ArrayList<>();
            for (File file : listFile){
                String excelName = file.getName();
                TabBeam tabBeam = new TabBeam();
                tabBeam.setUuid(uuid);
                try{
                    LiangExcelModelListener listener = new LiangExcelModelListener(vo,tabBeam,saveDataService,
                            cacheManager, system, excelName,uuid);
                    Sheet sheet = new Sheet(1, 0);
                    EasyExcelFactory.readBySax(new FileInputStream(file.getAbsolutePath()), sheet,listener);
                    if(null != cache.get(vo.getUuid() +"sb")){
                        TaskResultVo taskResultVo = cache.get(vo.getUuid() +"sb",TaskResultVo.class);
                        listFailed.addAll(taskResultVo.getListFailed());
                    }else{
                        cgNum = cgNum + 1;
                    }
                }catch (Exception e){
                    System.out.println(excelName);
                    sb.append(excelName+";");
                }

            }
            System.out.println("解析结束");
            map.put("成功条数",cgNum);
            map.put("失败数据",listFailed);
            tabServiceVo.setState(1);
            tabServiceVo.setFileUrl(userDir);
            tabDataSettingMapper.updateService(tabServiceVo);

            //返回信息
            map.put("tabService",tabServiceVo);
        }catch (Exception e){
            e.printStackTrace();
            return result.failure(500, "系统错误");
        }
        result.success(map);
        return result;
    }

    @Override
    public Result zhuImport(MultipartFile excelFile, ExcelInportBaseVo vo, TabUserVo tabUserVo) {
        Result result = new Result();
        Map<String,Object> map = new HashMap<>();
        try {
            String uuid = vo.getUuid();
            String userDir = System.getProperty("user.dir");

            //上传文件
            result = FileUpload.fileUpload(excelFile,userDir,uuid);
            userDir = (String)result.getData();


            String fileName1 = excelFile.getName();
            vo.setFileName(fileName1);
            // 获取文件名
            String fileName = excelFile.getOriginalFilename();
            // 获取文件的后缀名
            vo.setFileName(fileName.substring(0,fileName.lastIndexOf(".")));

            //发布服务
            SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMddHHmmss");
            String serviceName = vo.getFileName()+sdf1.format(new Date());
            TabServiceVo tabServiceVo = new TabServiceVo();
            tabServiceVo.setServiceUrl(earthUrl+serviceName);
            //根据用户查询用户
            tabServiceVo.setUserId(tabUserVo.getId());

            tabServiceVo.setName(serviceName);
            tabServiceVo.setReleaseTime(new Date());
            tabServiceVo.setServiceType(ServiceTypeEnum.ZHU.getValue());
            tabServiceVo.setUuid(vo.getUuid());

            tabDataSettingMapper.saveService(tabServiceVo);
            tabDataSettingMapper.saveUserService(tabServiceVo.getUserId(),tabServiceVo.getId());
            TabCoordinateSystem system = new TabCoordinateSystem();
            if(1 == vo.getIsChange()){
                system = tabMouldMapper.getCoorByName(vo.getCoorName());
            }
            //解压文件
            String zipUrl = userDir.substring(0,userDir.lastIndexOf(File.separator))+File.separator+uuid;
            ZipUtil.unZip(userDir,zipUrl);
            List<File> listFile = FileUtil.recursionFile(zipUrl,null);
            System.out.println("解析开始");
            Cache cache = cacheManager.getCache("cache-data");
            //失败数据
            StringBuffer sb = new StringBuffer();
            Integer cgNum = 0;
            List<ExcelInFailedDataVo> listFailed = new ArrayList<>();
            for (File file : listFile){
                String excelName = file.getName();
                TabPillar tabPillar = new TabPillar();
                tabPillar.setUuid(uuid);
                try{
                    PillarExcelModelListener listener = new PillarExcelModelListener(vo,tabPillar, saveDataService,
                            cacheManager, system, excelName,uuid);
                    Sheet sheet = new Sheet(1, 0);
                    EasyExcelFactory.readBySax(new FileInputStream(file.getAbsolutePath()), sheet,listener);
                    if(null != cache.get(uuid +"sb")){
                        TaskResultVo taskResultVo = cache.get(uuid +"sb",TaskResultVo.class);
                        listFailed.addAll(taskResultVo.getListFailed());
                    }else{
                        cgNum = cgNum + 1;
                    }
                }catch (Exception e){
                    System.out.println(excelName);
                    sb.append(excelName+";");
                }

            }
            System.out.println("解析结束");
            map.put("成功条数",cgNum);
            map.put("失败数据",listFailed);
            tabServiceVo.setState(1);
            tabServiceVo.setFileUrl(userDir);
            tabDataSettingMapper.updateService(tabServiceVo);

            //返回信息
            map.put("tabService",tabServiceVo);
        }catch (Exception e){
            e.printStackTrace();
            return result.failure(500, "系统错误");
        }
        result.success(map);
        return result;
    }

    @Override
    public Result liveImport(MultipartFile excelFile, TabExcelVo vo, TabUserVo tabUserVo) {
        Result result = new Result();
        Map<String,Object> map = new HashMap<>();
        Integer serviceId = null;
        try {
            //导入参数设置
            if(null == vo.getTitleRows()){
                return result.failure(-1,"标题所在行需指定");
            }
            String uuid = vo.getUuid();
            String userDir = System.getProperty("user.dir");
            String fileName1 = excelFile.getName();
            vo.setFileName(fileName1);
            if(null == vo.getStartRows()){
                vo.setStartRows(vo.getTitleRows()+1);
            }
            // 获取文件名
            String fileName = excelFile.getOriginalFilename();
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            vo.setFileName(fileName.substring(0,fileName.lastIndexOf(".")));
            userDir = userDir.substring(0,userDir.lastIndexOf(File.separator))+File.separator+"Upload"+File.separator+"excel"+File.separator+uuid+suffixName;

            //发布服务
            SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMddHHmmss");
            String serviceName = vo.getFileName()+sdf1.format(new Date());
            TabServiceVo tabServiceVo = new TabServiceVo();
            tabServiceVo.setServiceUrl(earthUrl+serviceName);
            //根据用户查询用户
            tabServiceVo.setUserId(tabUserVo.getId());

            tabServiceVo.setName(serviceName);
            tabServiceVo.setReleaseTime(new Date());
            tabServiceVo.setServiceType(ServiceTypeEnum.PTEXCEL.getValue());
            tabServiceVo.setUuid(vo.getUuid());

            tabDataSettingMapper.saveService(tabServiceVo);
            tabDataSettingMapper.saveUserService(tabServiceVo.getUserId(),tabServiceVo.getId());
            serviceId = tabServiceVo.getId();

            TabCoordinateSystem system = new TabCoordinateSystem();
            if(1 == vo.getIsChange()){
                system = tabMouldMapper.getCoorByName(vo.getCoorName());
                try{
                    XyChangeUtil.change(1d, 1d,system.getCoorChangeLat());
                }catch (Exception e){
                    e.printStackTrace();
                    tabDataSettingMapper.delTabService(serviceId);
                    tabDataSettingMapper.delUserService(serviceId);
                    return result.failure(-1,"请选择正确的坐标转换公式");
                }
            }
            ExcelPTListener listener = new ExcelPTListener(vo,cacheManager,system,tabUserVo.getId());
            Sheet sheet = new Sheet(1, 0);
            EasyExcelFactory.readBySax(excelFile.getInputStream(), sheet,listener);


            Cache cache = cacheManager.getCache("cache-data");
            ExcelBaseResultVo resultVo = cache.get(vo.getUuid()+"result",ExcelBaseResultVo.class);
            //去重
            List<TabBaseExcel> baseExcels = resultVo.getListBase().stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getLon()+":"+o.getLat()))), ArrayList::new));
            //如果工程不存在则删除已有数据，导入失败
            if(baseExcels.isEmpty()){
                tabDataSettingMapper.delTabService(serviceId);
                tabDataSettingMapper.delUserService(serviceId);
                return result.failure(-1, "导入数据缺少必要信息");
            }
            //保存数据
            Integer zkNum = baseExcels.size()/MAX_NUM + (baseExcels.size()%MAX_NUM>0?1:0);
            saveBatch(zkNum,baseExcels);
            tabServiceVo.setState(1);
            tabServiceVo.setFileUrl(userDir);
            tabDataSettingMapper.updateService(tabServiceVo);
            File file = new File(userDir);
            // 检测是否存在目录
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            excelFile.transferTo(file);

            Integer sbNum = resultVo.getListFailed().size();
            map.put("失败数据",resultVo.getListFailed());
            map.put("成功条数",baseExcels.size()-sbNum);
            //返回信息
            map.put("tabService",tabServiceVo);
        }catch (Exception e){
            e.printStackTrace();
            tabDataSettingMapper.delTabService(serviceId);
            tabDataSettingMapper.delUserService(serviceId);
            return result.failure(-1, "系统错误");
        }
        result.success(map);
        return result;
    }


    @Override
    public Result listMould() {
        Result result = new Result();
        List<TabExcelMould> list = tabMouldMapper.listMould();
        result.setData(list);
        return result;
    }

    @Override
    public Result listByMouldId(Integer mouldId) {
        Result result = new Result();
        List<TabMouldDetail> list = tabMouldMapper.listByMouldId(mouldId);
        result.setData(list);
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Result saveMould(TabMouldDetailVo vo) {
        Result result = new Result();
        if(null == vo.getMouldName()){
            return result.failure(404,"模板名称不能为空");
        }
        //检查模板名称是否重复
        TabExcelMould mould = tabMouldMapper.getByName(vo.getMouldName());
        if(null != mould){
            return result.failure(415,"模板名称已存在");
        }
        mould = new TabExcelMould();
        mould.setMouldName(vo.getMouldName());
        tabMouldMapper.saveMould(mould);
        Integer mouldId = mould.getId();
        List<DetailVo> details = vo.getDetails();
        TabMouldDetail tabMouldDetail = null;
        for (DetailVo detail:details) {
            tabMouldDetail = new TabMouldDetail();
            tabMouldDetail.setMouldId(mouldId);
            tabMouldDetail.setMouldKey(detail.getMouldKey());
            tabMouldDetail.setTableField(detail.getTableField());
            tabMouldDetail.setMouldCol(detail.getMouldCol());
            tabMouldDetail.setMouldOrigin(detail.getMouldOrigin());
            tabMouldMapper.saveMouldDetail(tabMouldDetail);
        }
        result.setData(mould);
        return result;
    }

    @Override
    public Result upMould(TabMouldDetailVo vo) {
        Result result = new Result();
        if(null == vo.getId()){
            return result.failure(404,"模板id不能为空");
        }
        //检查模板名称是否重复
        TabExcelMould mould = tabMouldMapper.getByName(vo.getMouldName());
        if(null != mould && !mould.getId().equals(vo.getId())){
            return result.failure(415,"模板名称已存在");
        }
        //删除详情
        tabMouldMapper.delByMouldId(vo.getId());
        List<DetailVo> details = vo.getDetails();
        TabMouldDetail tabMouldDetail = null;
        for (DetailVo detail:details) {
            tabMouldDetail = new TabMouldDetail();
            tabMouldDetail.setMouldId(vo.getId());
            tabMouldDetail.setMouldKey(detail.getMouldKey());
            tabMouldDetail.setTableField(detail.getTableField());
            tabMouldDetail.setMouldCol(detail.getMouldCol());
            tabMouldDetail.setMouldOrigin(detail.getMouldOrigin());
            tabMouldMapper.saveMouldDetail(tabMouldDetail);
        }
        TabExcelMould upMould = new TabExcelMould();
        upMould.setId(vo.getId());
        upMould.setMouldName(vo.getMouldName());
        tabMouldMapper.upMould(upMould);
        result.setData(upMould);
        return result;
    }

    @Override
    public Result delMould(Integer id) {
        Result result = new Result();
        //删除mould
        tabMouldMapper.delMould(id);
        //删除详情
        tabMouldMapper.delByMouldId(id);
        return result;
    }

    @Override
    public Result getCoorForm() {
        Result result = new Result();
        List<TabCoordinateSystem> list = tabMouldMapper.getCoorForm();
        for (TabCoordinateSystem system:list) {
            BigDecimal lon = XyChangeUtil.change(1d,1d,system.getCoorChangeLon());
            BigDecimal lat = XyChangeUtil.change(1d,1d,system.getCoorChangeLat());
            if(lon.compareTo(BigDecimal.ZERO)==0 || lat.compareTo(BigDecimal.ZERO)==0){
                system.setDisable(Boolean.TRUE);
            }
        }
        return result.success(list);
    }

    @Override
    public Result saveCoorForm(TabCoordinateSystem system) {
        Result result = new Result();
        tabMouldMapper.saveTabCoordinateSystem(system);
        return result.success("操作成功");
    }

}
